package user.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import LOGIN.login; // 确保这是正确的登录页面路径
import com.example.xfengshopping.R;



public class UserFragment extends Fragment {

    private static final String TAG = "UserFragment";
    private static final String PREFS_NAME = "AppPrefs";

    private Context mContext;
    private View rootView;
    private SharedPreferences sharedPreferences;
    private boolean hasCheckedLogin = false; // 防止重复跳转的标志

    // UI组件
    private ImageView backButton;
    private ImageView profileImage;
    private EditText nameEditText, loginEditText, signatureEditText;
    private TextView orderText, accountText, addressText, aboutText;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mContext = context;
        sharedPreferences = mContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        Log.d(TAG, "SharedPreferences initialized");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_user, container, false);
        initView();
        checkUserStatus();
        initData();
        initListener();
        return rootView;
    }

    /**
     * 检查用户登录状态
     * 只检查是否登录，不检查注册状态
     */
    private void checkUserStatus() {
        if (hasCheckedLogin) {
            Log.d(TAG, "Already checked login status, skip");
            return;
        }

        boolean isLoggedIn = sharedPreferences.contains("user_token");
        Log.d(TAG, "Login status: " + isLoggedIn);

        if (!isLoggedIn) {
            Log.d(TAG, "User not logged in, navigating to login");
            navigateToLogin();
            hasCheckedLogin = true;
        } else {
            Log.d(TAG, "User already logged in, loading info");
            loadUserInfo();
        }
    }

    private void navigateToLogin() {
        Log.d(TAG, "Starting login activity");
        Intent intent = new Intent(mContext, login.class);
        startActivity(intent);
    }

    private void loadUserInfo() {
        String nickname = sharedPreferences.getString("nickname", "未设置昵称");
        String loginName = sharedPreferences.getString("loginName", "未设置登录名"); // 读取登录名
        String signature = sharedPreferences.getString("signature", "暂无个性签名");

        nameEditText.setText(nickname);
        loginEditText.setText(loginName); // 设置登录名到输入框
        signatureEditText.setText(signature);

        Log.d(TAG, "User info loaded: " + nickname);
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "Fragment resumed, resetting check flag");
        hasCheckedLogin = false; // 重置标志，允许重新检查
        checkUserStatus();
    }

    private void initView() {
        backButton = rootView.findViewById(R.id.iv_left);
        nameEditText = rootView.findViewById(R.id.person_name_edit); // 昵称显示框，对应布局中的昵称EditText
        signatureEditText = rootView.findViewById(R.id.person_nature_edit); // 个性签名显示框
        backButton = rootView.findViewById(R.id.iv_left);
        profileImage = rootView.findViewById(R.id.person_1);
        nameEditText = rootView.findViewById(R.id.person_name_edit);
        loginEditText = rootView.findViewById(R.id.person_number_edit);
        signatureEditText = rootView.findViewById(R.id.person_nature_edit);
        orderText = rootView.findViewById(R.id.person_my);
        accountText = rootView.findViewById(R.id.person_zhanghao);
        addressText = rootView.findViewById(R.id.person_addrest);
        aboutText = rootView.findViewById(R.id.person_with);

        Log.d(TAG, "UI components initialized");
    }

    private void initData() {
        if (!sharedPreferences.contains("user_token")) {
            nameEditText.setText("请先登录");
            loginEditText.setText("");
            signatureEditText.setText("点击登录后显示信息");
            Log.d(TAG, "Default data set for non-logged user");
        }
    }

    private void initListener() {
        backButton.setOnClickListener(v -> {
            if (getActivity() != null) {
                getActivity().onBackPressed();
            }
        });

        orderText.setOnClickListener(v -> {
            if (mContext == null) {
                Log.e(TAG, "Context is null, cannot start activity");
                return;
            }
            if (sharedPreferences.contains("user_token")) {
                Intent intent = new Intent(mContext, OrderListActivity.class);
                startActivity(intent);
            } else {
                showToast("请先登录");
                navigateToLogin();
            }
        });

        accountText.setOnClickListener(v -> {
            if (sharedPreferences.contains("user_token")) {
                Intent intent = new Intent(mContext, AccountManagement.class);
                startActivity(intent);
            } else {
                showToast("请先登录");
                navigateToLogin();
            }
        });

        addressText.setOnClickListener(v -> {
            if (sharedPreferences.contains("user_token")) {
                Intent intent = new Intent(mContext, AddressManagementActivity.class);
                startActivity(intent);
            } else {
                showToast("请先登录");
                navigateToLogin();
            }
        });
    }

    private void showToast(String message) {
        if (getActivity() != null) {
            Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
        }
    }

    public interface OnNavigateToUserFragmentListener {
        void onNavigateToUserFragment();
    }
}